<template>
  <div class="create-plan-bg">
    <el-steps :active="step - 1" finish-status="success" align-center style="margin-bottom: 32px">
      <el-step title="选择计划模板" />
      <el-step title="计划参数设置" />
      <el-step title="确认创建" />
    </el-steps>

    <div v-if="step === 1">
      <div class="plan-template-list">
        <el-card v-for="tpl in templates" :key="tpl.key" :class="['plan-template', { selected: selectedTemplate === tpl.key }]" @click="selectTemplate(tpl.key)">
          <div class="plan-template-title">{{ tpl.name }}</div>
          <div class="plan-template-desc">{{ tpl.desc }}</div>
          <el-icon v-if="selectedTemplate === tpl.key" color="#409EFF"><i-ep-Check /></el-icon>
        </el-card>
      </div>
      <el-button type="primary" :disabled="!selectedTemplate" @click="nextStep" class="next-btn">下一步：设置参数</el-button>
    </div>

    <div v-else-if="step === 2">
      <div class="plan-form-bg">
        <el-form label-width="120px" class="plan-form">
          <el-form-item v-if="selectedTemplate === 'custom'" label="计划天数">
            <el-input-number 
              v-model="params.customDays" 
              :min="1" 
              :max="60" 
              :step="1"
              @change="handleDaysChange"
            />
            <span class="days-tip">（1-60天）</span>
          </el-form-item>
          <el-form-item label="每日总题量">
            <el-slider v-model="params.totalQuestions" :min="5" :max="100" show-input />
          </el-form-item>
          <el-form-item label="选择科目">
            <el-checkbox-group v-model="params.selectedSubjects">
              <el-checkbox label="高等数学" />
              <el-checkbox label="概率论" />
              <el-checkbox label="线性代数" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item v-if="params.selectedSubjects.length > 1" label=" ">
            <el-card shadow="always" :key="params.selectedSubjects.join(',')" class="subject-ratio-card">
              <div class="subject-ratio-title">科目比例分配</div>
              <div class="subject-ratio-list">
                <div v-for="sub in subjectRatioOptions" :key="sub.key" v-show="params.selectedSubjects.includes(sub.label)" class="subject-ratio-item">
                  <el-input-number v-model="params.subjectRatio[sub.key]" :min="0" :max="100" />
                  <span class="subject-ratio-label">{{ sub.label }}</span>
                </div>
              </div>
              <div class="subject-ratio-tip">总和应为100%</div>
            </el-card>
          </el-form-item>
          <el-form-item label="智能推荐">
            <el-switch v-model="params.smartRecommend" />
          </el-form-item>
          <el-form-item v-if="params.smartRecommend" >
            <div class="weak-points">
              <h3>薄弱知识点</h3>
              <div class="weak-points-list">
                <div v-for="item in weakPointOptions" :key="item.pointId" class="weak-point-card">
                  <el-checkbox :label="item.label" class="weak-point-checkbox">
                    <span class="weak-point-label">
                      <el-icon style="vertical-align: middle; color: #67C23A; margin-right: 6px;"><i-ep-Check /></el-icon>
                      {{ item.label }}
                    </span>
                    <el-progress :percentage="item.rate" :stroke-width="16" status="success" style="width: 120px; margin-left: 12px; vertical-align: middle;" />
                    <span class="weak-point-rate">准确率：{{ item.rate }}%</span>
                  </el-checkbox>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="plan-step-btns">
        <el-button @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="nextStep" :disabled="!isParamValid">下一步：确认创建</el-button>
      </div>
    </div>

    <div v-else-if="step === 3">
      <el-card class="plan-overview-card">
        <div class="plan-overview-title">计划概览</div>
        <el-form label-width="120px" class="plan-form">
          <el-form-item label="计划名称">
            <el-input v-model="overview.planName" placeholder="请输入计划名称" />
          </el-form-item>
          <el-form-item label="计划周期">
            <el-input v-model="overview.planPeriod" placeholder="如：7天（1周）" />
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="overview.startDate"
              type="date"
              :disabled-date="disabledPastDate"
              placeholder="选择开始日期"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="每日题量">
            <el-input v-model="overview.totalQuestions" readonly />
          </el-form-item>
          <el-form-item label="包含科目">
            <div style="display: flex; gap: 16px; flex-wrap: wrap;">
              <el-tag 
                v-for="subject in overview.selectedSubjects" 
                :key="subject" 
                type="success" 
                size="large"
                style="font-size: 14px; padding: 8px 16px;"
              >
                {{ subject }}
              </el-tag>
              <span v-if="overview.selectedSubjects.length === 0" style="color: #909399; font-size: 14px;">
                未选择任何科目
              </span>
            </div>
          </el-form-item>
          <el-form-item v-if="overview.weakPoints.length > 0" label="强化知识点">
            <el-tag v-for="wp in overview.weakPoints" :key="wp" type="danger">{{ wp }}</el-tag>
          </el-form-item>
          <el-form-item label="科目比例">
            <div style="display: flex; justify-content: flex-start; gap: 32px;">
              <template v-if="overview.selectedSubjects.includes('高等数学')">
                <span style="white-space: nowrap; color: #409EFF; font-weight: bold;">{{ overview.subjectRatio.math }}%</span>
                <span style="white-space: nowrap; margin-right: 16px;">高数</span>
              </template>
              <template v-if="overview.selectedSubjects.includes('线性代数')">
                <span style="white-space: nowrap; color: #409EFF; font-weight: bold;">{{ overview.subjectRatio.linear }}%</span>
                <span style="white-space: nowrap; margin-right: 16px;">线代</span>
              </template>
              <template v-if="overview.selectedSubjects.includes('概率论')">
                <span style="white-space: nowrap; color: #409EFF; font-weight: bold;">{{ overview.subjectRatio.prob }}%</span>
                <span style="white-space: nowrap;">概率论</span>
              </template>
            </div>
          </el-form-item>
          <el-form-item label="计划日历预览">
            <el-row :gutter="8">
              <el-col v-for="(day, idx) in overview.calendar" :key="idx" :span="6">
                <div class="plan-calendar-card">
                  <div style="font-weight: bold; margin-bottom: 4px;">第{{ idx + 1 }}天</div>
                  <div style="font-size: 14px;">
                    {{ day }}
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-card>
      <div class="plan-step-btns">
        <el-button @click="prevStep">上一步</el-button>
        <el-button 
          type="primary" 
          @click="debouncedCreatePlan" 
          style="margin-left: 8px;" 
          :loading="loading"
          :disabled="loading || isCreating"
        >创建</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, h, createVNode, defineComponent } from 'vue'
import { ElMessage, ElMessageBox, ElSelect, ElOption } from 'element-plus'
import { Check as IepCheck, WarningFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const step = ref(1)
const selectedTemplate = ref('')
const loading = ref(false)
const isCreating = ref(false)
const templates = [
  { key: 'sprint', name: '冲刺型周计划', desc: '高强度七天密集训练，适合考前冲刺' },
  { key: 'balance', name: '均衡型月计划', desc: '科目轮换学习，30天科学分配' },
  { key: 'custom', name: '自定义计划', desc: '完全自主设置，灵活安排学习' }
]

const params = ref({
  totalQuestions: 14,
  subjectRatio: { math: 40, linear: 30, prob: 30 },
  selectedSubjects: ['高等数学', '概率论', '线性代数'],
  smartRecommend: true,
  weakPoints: [],
  customDays: 7,
  difficultyLevel: 1
})

const weakPointOptions = ref([])

const subjectRatioOptions = [
  { key: 'math', label: '高等数学' },
  { key: 'linear', label: '线性代数' },
  { key: 'prob', label: '概率论' }
]

const difficultyLevels = ref([])

const planName = computed(() => {
  if (selectedTemplate.value === 'sprint') return '高数7天冲刺计划'
  if (selectedTemplate.value === 'balance') return '高数30天突破计划'
  return '自定义学习计划'
})
const planPeriod = computed(() => {
  if (selectedTemplate.value === 'balance') return '30天（1个月）'
  if (selectedTemplate.value === 'custom') return `${params.value.customDays}天`
  return '7天（1周）'
})
const startDate = ref('2023-07-01')
const studyTime = '早晨（6:00-9:00）、晚上（19:00-22:00）'

const generateDayContent = (dayIndex, template, params) => {
  // 复习日逻辑
  if (dayIndex % 7 === 6) {
    return '复习日';
  }

  // 根据模板类型生成内容
  switch (template) {
    case 'sprint':
    case 'balance':
    case 'custom':
      return generateCustomDayContent(params);
    
    default:
      return '自定义';
  }
};

const generateCustomDayContent = (params) => {
  const { totalQuestions, subjectRatio, selectedSubjects } = params;
  
  // 验证输入参数
  if (!totalQuestions || !subjectRatio || !selectedSubjects?.length) {
    return '自定义';
  }
        
        // 计算每个科目的题目数量
        const subjectQuestions = {};
  const subjectMap = {
    '高等数学': { key: '高数', ratio: 'math' },
    '线性代数': { key: '线代', ratio: 'linear' },
    '概率论': { key: '概率论', ratio: 'prob' }
  };

  // 计算每个科目的题目数量，确保总和等于totalQuestions
  let remainingQuestions = totalQuestions;
  const sortedSubjects = [...selectedSubjects].sort((a, b) => 
    subjectRatio[subjectMap[b].ratio] - subjectRatio[subjectMap[a].ratio]
  );

  sortedSubjects.forEach((subject, index) => {
    const subjectInfo = subjectMap[subject];
    if (subjectInfo) {
      let count;
      if (index === sortedSubjects.length - 1) {
        // 最后一个科目，使用剩余题目数
        count = remainingQuestions;
      } else {
        // 根据比例计算题目数，向下取整
        count = Math.floor(totalQuestions * subjectRatio[subjectInfo.ratio] / 100);
        remainingQuestions -= count;
      }
      if (count > 0) {
        subjectQuestions[subjectInfo.key] = count;
      }
          }
        });

        // 生成当天的任务内容
  return Object.entries(subjectQuestions)
          .map(([subject, count]) => `${subject}${count}题`)
    .join('\n') || '自定义';
};

const calendarPreview = computed(() => {
  const days = selectedTemplate.value === 'balance' ? 30 : 
              selectedTemplate.value === 'custom' ? params.value.customDays : 7;
  
  return Array.from({ length: days }, (_, i) => 
    generateDayContent(i, selectedTemplate.value, params.value)
  );
})

// 添加临时存储选择值的 ref
const tempDifficultyLevel = ref(1)

// 创建难度选择组件
const DifficultySelect = defineComponent({
  props: {
    modelValue: {
      type: Number,
      required: true
    },
    options: {
      type: Array,
      required: true
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const selectedValue = ref(props.modelValue)
    
    watch(() => props.modelValue, (newVal) => {
      selectedValue.value = newVal
    })
    
    const handleChange = (val) => {
      selectedValue.value = val
      emit('update:modelValue', val)
    }
    
    return () => createVNode('div', { style: 'padding: 20px 0;' }, [
      createVNode('div', { style: 'margin-bottom: 16px;' }, '请选择考试类型：'),
      createVNode(ElSelect, {
        modelValue: selectedValue.value,
        'onUpdate:modelValue': handleChange,
        style: 'width: 100%;',
        placeholder: '请选择类型'
      }, () => 
        props.options.map(level => 
          createVNode(ElOption, {
            key: level.value,
            label: '数' + level.label,
            value: level.value
          })
        )
      )
    ])
  }
})

const questions = ref([])

// 添加科目ID映射
const subjectIdMap = {
  "高等数学": 1,
  "概率论": 2,
  "线性代数": 3
};

async function selectTemplate(key) {
  if (key === 'custom') {
    try {
      const { value: days } = await ElMessageBox.prompt('请输入计划天数（大于0的正整数）', '自定义计划', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^([1-9]|[1-5][0-9]|60)$/,
        inputErrorMessage: '请输入大于1的正整数',
        inputType: 'number',
        inputValue: '7'
      })
      
      if (days) {
        params.value.customDays = parseInt(days)
        selectedTemplate.value = key
      }
    } catch (error) {
      // 用户取消输入
      return
    }
  } else {
    selectedTemplate.value = key
  }
}
async function nextStep() {
  if (step.value === 1 && !selectedTemplate.value) {
    ElMessage.warning('请选择一个计划模板')
    return
  }
  
  if (step.value === 2) {
    if (!isParamValid.value) {
      ElMessage.warning('请完善参数设置')
      return
    }
    
    // 初始化临时值
    tempDifficultyLevel.value = params.value.difficultyLevel
    
    try {
      // 弹出考试类型选择框
      await ElMessageBox({
        title: '选择考试类型',
        message: createVNode(DifficultySelect, {
          modelValue: tempDifficultyLevel.value,
          'onUpdate:modelValue': (val) => {
            tempDifficultyLevel.value = val
            console.log('选择的考试类型:', val)
          },
          options: difficultyLevels.value
        }),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'difficulty-select-dialog',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            // 确认时更新实际的值
            params.value.difficultyLevel = tempDifficultyLevel.value
            console.log('确认选择考试类型:', params.value.difficultyLevel)
            
            // 获取并筛选题目
            await fetchQuestions()
            
            // 如果没有可用题目，阻止进入下一步
            if (questions.value.length === 0) {
              ElMessage.warning('当前考试类型下没有可用题目，请重新选择')
              return
            }
            
            // 检查筛选后的题目数量是否足够
            const totalDays = Math.ceil((new Date(params.value.endDate) - new Date(params.value.startDate)) / (1000 * 60 * 60 * 24)) + 1
            const totalQuestions = params.value.questionsPerDay * totalDays
            
            if (questions.value.length < totalQuestions) {
              ElMessage.warning(`当前考试类型下题目数量不足，需要${totalQuestions}道题目，但只有${questions.value.length}道题目可用`)
              return
            }
            
            done()
            step.value++
          } else {
            done()
          }
        }
      })
    } catch (error) {
      // 用户取消选择
      return
    }
  } else {
    step.value++
  }
}
function prevStep() {
  if (step.value > 1) step.value--
}
const isParamValid = computed(() => {
  const ratio = params.value.subjectRatio
  const subjectCount = params.value.selectedSubjects.length
  const ratioSum = ratio.math + ratio.linear + ratio.prob
  // 只要选了多个科目，比例和必须为100，否则不校验比例
  return params.value.totalQuestions > 0 && params.value.selectedSubjects.length > 0 && (subjectCount <= 1 || ratioSum === 100)
})

const userStore = useUserStore();

const checkLoginStatus = () => {
  const userId = userStore.userId || (userStore.user && userStore.user.userId);
  console.log('Pinia userId:', userId);
  return !!userId;
};

async function fetchWeakPoints() {
  try {
    const loginStatus = checkLoginStatus();
    if (!loginStatus) {
      ElMessage.error('请先登录');
      return;
    }
    const userId = userStore.userId || (userStore.user && userStore.user.userId);
    console.log('fetchWeakPoints userId:', userId);
    const response = await axios.get('/api/z/weak-points', {
      params: {
        userId: userId,
        page: 1,
        size: 100
      }
    });
    
    console.log('API Response:', response.data);
    
    if (response.data && response.data.code === 200 && response.data.data && response.data.data.list) {
      weakPointOptions.value = response.data.data.list.map(item => ({
        label: item.label || '',
        rate: item.wrongRate || 0,
        pointId: item.pointId || '',
        subjectId: item.subjectId || ''
      }));
      
      console.log('weakPointOptions after assignment:', JSON.stringify(weakPointOptions.value));
    } else {
      console.warn('API response format:', response.data);
      ElMessage.warning('获取薄弱知识点数据格式不正确');
    }
  } catch (error) {
    ElMessage.error('获取薄弱知识点失败');
    console.error('获取薄弱知识点失败:', error);
  }
}

async function fetchDifficultyLevels() {
  try {
    const response = await axios.get('/api/favorites/difficulty-levels')
    console.log('fetchDifficultyLevels response:', response)
    if (response.status === 200) {
      difficultyLevels.value = response.data.map(item => ({
        value: item.value,
        label: item.value
        // label: getDifficultyLabel(item.value)
      }))
    }
  } catch (error) {
    console.error('获取难度级别失败:', error)
    ElMessage.error('获取难度级别失败')
  }
}

onMounted(() => {
  console.log('Component mounted, checking login status...');
  const loginStatus = checkLoginStatus();
  console.log('Initial login status:', loginStatus);
  if (loginStatus) {
    fetchWeakPoints();
    fetchDifficultyLevels();
  } else {
    console.warn('User is not logged in');
  }
});

const today = new Date();
const formatDate = (date) => {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
};

const overview = ref({
  planName: '',
  planPeriod: '',
  startDate: formatDate(today),
  totalQuestions: 0,
  selectedSubjects: [],
  subjectRatio: { math: 0, linear: 0, prob: 0 },
  weakPoints: [],
  calendar: []
});

function syncOverviewFromParams() {
  console.log('同步数据到概览 - 第二步数据:', {
    selectedSubjects: params.value.selectedSubjects,
    subjectRatio: params.value.subjectRatio,
    totalQuestions: params.value.totalQuestions,
    weakPoints: params.value.weakPoints
  });
  
  overview.value.planName = planName.value;
  overview.value.planPeriod = planPeriod.value;
  overview.value.startDate = formatDate(today);
  overview.value.totalQuestions = params.value.totalQuestions;
  overview.value.selectedSubjects = [...params.value.selectedSubjects];
  overview.value.subjectRatio = { ...params.value.subjectRatio };
  overview.value.weakPoints = [...params.value.weakPoints];
  overview.value.calendar = [...calendarPreview.value];
  
  if (overview.value.selectedSubjects.length === 1) {
    const subject = overview.value.selectedSubjects[0];
    if (subject === '高等数学') {
      overview.value.subjectRatio.math = 100;
      overview.value.subjectRatio.linear = 0;
      overview.value.subjectRatio.prob = 0;
    } else if (subject === '线性代数') {
      overview.value.subjectRatio.math = 0;
      overview.value.subjectRatio.linear = 100;
      overview.value.subjectRatio.prob = 0;
    } else if (subject === '概率论') {
      overview.value.subjectRatio.math = 0;
      overview.value.subjectRatio.linear = 0;
      overview.value.subjectRatio.prob = 100;
    }
  }
  
  console.log('同步完成 - 概览数据:', {
    selectedSubjects: overview.value.selectedSubjects,
    subjectRatio: overview.value.subjectRatio,
    totalQuestions: overview.value.totalQuestions,
    weakPoints: overview.value.weakPoints
  });

  generateCalendar();
}

watch(step, (val) => {
  if (val === 3) {
    syncOverviewFromParams();
  }
});

watch(
  () => overview.value.totalQuestions,
  (newTotal) => {
    if (step.value === 3) {
      console.log('第三步每日题量变化:', newTotal);
      params.value.totalQuestions = newTotal;
    }
  }
);

const disabledPastDate = (date) => date < new Date(new Date().setHours(0,0,0,0));

function generateCalendar() {
  // 如果还没有获取题目，先获取题目
  if (questions.value.length === 0) {
    ElMessage.warning('请先选择考试类型并获取题目')
    return []
  }
  
  const calendar = []
  const startDate = new Date(params.value.startDate)
  const endDate = new Date(params.value.endDate)
  
  const totalDays = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1
  const totalQuestions = params.value.questionsPerDay * totalDays
  
  if (totalQuestions > questions.value.length) {
    ElMessage.warning(`题目数量不足，需要${totalQuestions}道题目，但只有${questions.value.length}道题目可用`)
    return []
  }
  
  let questionIndex = 0
  for (let i = 0; i < totalDays; i++) {
    const currentDate = new Date(startDate)
    currentDate.setDate(startDate.getDate() + i)
    
    const dayQuestions = []
    for (let j = 0; j < params.value.questionsPerDay; j++) {
      if (questionIndex < questions.value.length) {
        dayQuestions.push(questions.value[questionIndex])
        questionIndex++
      }
    }
    
    calendar.push({
      date: currentDate.toISOString().split('T')[0],
      questions: dayQuestions,
      studyTime: params.value.studyTime,
      reviewTime: params.value.reviewTime
    })
  }
  
  return calendar
}

// 防抖函数
function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 添加状态映射
const STATUS_MAP = {
  '未完成': 'pending',
  '已完成': 'completed',
  '已跳过': 'skipped'
}

// 修改创建计划时的状态
const debouncedCreatePlan = debounce(async () => {
  if (loading.value || isCreating.value) return
  loading.value = true
  isCreating.value = true
  
  const userId = userStore.userId
  const calendar = overview.value.calendar
  const startDate = new Date(overview.value.startDate)
  const planId = Date.now()

  try {
    // 检查questions是否存在且有值
    console.log('questions:', questions.value)
    if (!questions.value || questions.value.length === 0) {
      ElMessage.error('请先选择考试类型并获取题目')
      return
    }

    // 先创建学习计划
    const planData = {
      userId: userId,
      planName: overview.value.planName,
      startDate: overview.value.startDate,
      endDate: new Date(startDate.getTime() + (calendar.length - 1) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      totalDays: calendar.length,
      totalQuestions: params.value.totalQuestions,
      selectedSubjects: params.value.selectedSubjects,
      subjectRatio: params.value.subjectRatio,
      difficultyLevel: params.value.difficultyLevel,
      content: `学习计划：${overview.value.planName}，共${calendar.length}天，每日${params.value.totalQuestions}题，包含${params.value.selectedSubjects.join('、')}`,
      // 新增目标科目ID
      targetSubjectId: subjectIdMap[params.value.selectedSubjects[0]] || 1
    }

    const planResponse = await axios.post('/api/study-plans/create', planData)
    if (!planResponse.data || !planResponse.data.planId) {
      throw new Error('创建学习计划失败')
    }

    const tasks = []
    let questionIndex = 0  // 用于追踪当前使用的题目索引
    
    for (let i = 0; i < calendar.length; i++) {
      const dayContent = calendar[i]
      console.log('当前日期内容:', dayContent)
      
      // 跳过复习日或无效内容
      if (!dayContent || dayContent === '复习') {
        console.log('跳过复习日或无效内容')
        continue
      }

      const date = new Date(startDate)
      date.setDate(date.getDate() + i)
      const taskDate = date.toISOString().slice(0, 10)

      // 从内容中提取题目数量
      const matches = dayContent.match(/\d+/g)
      console.log('题目数量：', matches)
      if (!matches || matches.length === 0) {
        console.error('无法从内容中提取题目数量:', dayContent)
        continue
      }
      
      // 计算总题目数量
      let questionsCount = matches.reduce((sum, num) => sum + parseInt(num), 0)
      console.log('总题目数量：', questionsCount)

      const task = {
          userId,
          planId: planResponse.data.planId,
          content: dayContent,
          status: '未完成',
          deep: true,
        questionId: questions.value[questionIndex]?.questionId,
          taskDate: taskDate,
          //一天要做多少道题
          questionsCount: questionsCount
      }
      
      if (task.questionId) {
        tasks.push(task)
        questionIndex++
      }
    }

    console.log('准备创建的任务:', tasks)
    
    if (tasks.length === 0) {
      ElMessage.error('没有可创建的任务')
      return
    }
    
    // 使用Promise.all并发请求，并添加超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 30000) // 30秒超时
    })

    const promises = tasks.map(task => {
      console.log('task', task);
      return axios.post('/api/daily-tasks/add', task);
    });
    
    const results = await Promise.race([
      Promise.all(promises),
      timeoutPromise
    ])

    console.log('results', results)
    const successCount = results.filter(r => r.status === 200).length

    if (successCount > 0) {
      ElMessage.success('学习计划创建成功！')
      router.push('/study-plan/today')
    }
  } catch (e) {
    console.error('创建计划失败:', e)
    if (e.message === '请求超时') {
      ElMessage.error('创建超时，请重试')
    } else {
      ElMessage.error('创建失败，请重试')
    }
  } finally {
    loading.value = false
    isCreating.value = false
  }
}, 300)  // 300ms的防抖延迟

function handleDaysChange(value) {
  if (value < 1) {
    params.value.customDays = 1
  } else if (value > 60) {
    params.value.customDays = 60
  }
}

// 添加 watch 监听难度变化
watch(() => params.value.difficultyLevel, (newVal) => {
  console.log('难度变化:', newVal)
  // 重新获取题目
  fetchQuestions()
})

// 修改 fetchQuestions 函数
async function fetchQuestions() {
  try {
    const response = await axios.get('/api/questions/all')
    console.log('fetchQuestions response:', response)
    if (response.status === 200) {
      // 保存所有题目
      const allQuestions = response.data
      console.log('获取到的所有题目:', allQuestions)
      
      // 根据当前选择的考试类型筛选题目
      questions.value = allQuestions.filter(q => Number(q.typeId) === Number(params.value.difficultyLevel))
      console.log('筛选后的题目:', questions.value)
      
      // 如果筛选后没有题目，显示提示
      if (questions.value.length === 0) {
        ElMessage.warning('当前考试类型下没有可用题目')
        return false // 返回 false 表示获取题目失败
      }
      return true // 返回 true 表示获取题目成功
    } else {
      ElMessage.error(response.data.message || '获取题目失败')
      return false
    }
  } catch (error) {
    console.error('获取题目失败:', error)
    ElMessage.error('获取题目失败')
    return false
  }
}
</script>

<style scoped>
.create-plan-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e0e7ef 100%);
  padding: 32px 0 64px 0;
}
.plan-template-list {
  display: flex;
  gap: 32px;
  justify-content: center;
  margin-bottom: 32px;
}
.plan-template {
  border: 2px solid #ebeef5;
  border-radius: 12px;
  transition: border-color 0.2s, box-shadow 0.2s;
  background: #fff;
  min-width: 260px;
  min-height: 120px;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.06);
  cursor: pointer;
  padding: 24px 32px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  position: relative;
}
.plan-template.selected {
  border-color: #409EFF;
  background: #f0f9ff;
  box-shadow: 0 4px 24px rgba(64, 158, 255, 0.13);
}
.plan-template-title {
  font-weight: bold;
  font-size: 20px;
  color: #409EFF;
  margin-bottom: 8px;
}
.plan-template-desc {
  color: #888;
  font-size: 15px;
  margin-bottom: 8px;
}
.next-btn {
  float: right;
  margin-right: 80px;
  margin-top: 12px;
  font-size: 16px;
  padding: 10px 32px;
  border-radius: 8px;
}
.plan-form-bg {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64, 158, 255, 0.08);
  padding: 36px 48px 24px 48px;
  max-width: 900px;
  margin: 0 auto 32px auto;
}
.plan-form {
  width: 100%;
}
.subject-ratio-card {
  background: #f4f8ff;
  border: 1.5px solid #409EFF;
  margin-bottom: 12px;
  max-width: 1000px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.06);
}
.subject-ratio-title {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
  text-align: center;
  font-size: 17px;
}
.subject-ratio-list {
  display: flex;
  gap: 64px;
  justify-content: center;
  margin-bottom: 8px;
}
.subject-ratio-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 160px;
}
.subject-ratio-label {
  margin-top: 6px;
  font-size: 14px;
  color: #606266;
}
.subject-ratio-tip {
  color: #aaa;
  font-size: 12px;
  margin-top: 4px;
  text-align: center;
}
.weak-points {
  margin-top: 20px;
}

.weak-points h3 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.weak-points-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 8px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.weak-point-card {
  background: #f6ffed;
  border: 1.5px solid #67C23A;
  border-radius: 8px;
  padding: 12px 18px;
  display: flex;
  align-items: center;
  min-width: 260px;
  margin-bottom: 8px;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.06);
  transition: all 0.3s ease;
  flex: 1;
  max-width: calc(50% - 8px);
}

.weak-point-card:hover {
  box-shadow: 0 4px 16px rgba(103, 194, 58, 0.13);
  transform: translateY(-2px);
}

.weak-point-checkbox {
  width: 100%;
  margin-right: 0;
}

.weak-point-label {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.weak-points-list::-webkit-scrollbar {
  width: 6px;
}

.weak-points-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.weak-points-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.weak-points-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
.weak-point-rate {
  margin-left: 12px;
  color: #67C23A;
  font-size: 13px;
}
.plan-step-btns {
  display: flex;
  justify-content: space-between;
  margin-top: 32px;
  max-width: 900px;
  margin-left: auto;
  margin-right: auto;
}
.plan-overview-card {
  background: #f8fafc;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64, 158, 255, 0.08);
  padding: 36px 48px 24px 48px;
  max-width: 900px;
  margin: 0 auto 32px auto;
}
.plan-overview-title {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 8px;
  color: #409EFF;
}
.plan-calendar-title {
  margin: 24px 0 8px;
  font-weight: bold;
  color: #409EFF;
}
.plan-calendar-card {
  text-align: center;
  background: #f4f8ff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.06);
}
.plan-calendar-content {
  color: #67C23A;
  font-weight: 500;
  font-size: 15px;
  margin-top: 4px;
}
.days-tip {
  margin-left: 12px;
  color: #909399;
  font-size: 14px;
}

:deep(.el-input-number) {
  width: 180px;
}

:deep(.el-input-number .el-input__wrapper) {
  padding: 0 12px;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.difficulty-select-dialog) {
  .el-message-box__content {
    padding: 20px;
  }
  
  .el-select {
    width: 100%;
  }

  .el-input__wrapper {
    width: 100%;
  }
}
</style> 

